import Core.Basic
from Core.package import *




class Worker_Thread(QThread):
    thread_task_data = Signal(dict)
    def __init__(self, parent = None):
        super().__init__(parent)
        self.driver = Core.Basic.GlobalVar.driver
        self.task_data = dict()
    
    def run(self):
        try:
            print("线程任务完成!")
              
        except Exception as e:
            print(f"提示 : 员工线程任务发生错误!\n\
                    错误信息: {e}")
        finally:
            self.thread_task_data.emit(self.task_data)
        
        
        
        # 线程任务完成，会自动发送信号的,无需手动发送,手动发送可能会导致发送两遍信号.
        # self.finished.emit()
    def __delattr__(self, name):
        print(f"提示 : 子任务子线程运行结束!正在销毁资源 {self}")
        return super().__delattr__(name)
    

class Staff_Saveas_Upload_Config_File(QObject):
    Start_Task = Signal()   # 任务开始信号,启动任务时,请发送此信号
    Task_Finish = Signal()   # 任务完成信号,任务结束时候,请发送此信号
    Current_Completion_Process = Signal(int)
    Emergency_Stop = Signal()  # 紧急停止信号
    OnlyRun = Signal()  # 仅运行信号

    def __init__(self, parent=None):
        super().__init__(parent)
        self.Start_Task.connect(self.RunTask)
        
    @Slot(str)
    def slot_fun(self,text):
        print(f"我是槽函数,我是 {text}")

    # 设置员工属性
    def Set_Staff_Attribute(self,**kwargs):
        """设置员工对象的属性，用于后续任务执行
        """
        for key, value in kwargs.items():
            setattr(self, key, value)
        print(f"已设置属性: {kwargs.keys()}")

    def RunTask(self):

        # 获取需要操作的 主线程 窗口的 UI 对象
        # 使用 self.parent() 获取父对象
        self.parent_widget = self.parent()
        if self.parent_widget is None:
            print(f"提示 : 父对象为空!\n请将创建员工对象时,将父对象作为参数传入!")
            return
        # 获取 任务按钮 UI 控件对象
        self.task_button_object_name = "pushButton_update_localtion_upload_config"
        self.task_button : QPushButton = self.parent().findChild(QPushButton,self.task_button_object_name)
        if self.task_button is None:
            print(f"提示 : 程序无法找到 {self.task_button_object_name} 对应的按钮!")
            print(f"提示 : 子任务结束!")
            return
        self.comboBox_object_name = "comboBox_localtion_upload_config_file"
        self.comboBox : QComboBox = self.parent().findChild(QComboBox,self.comboBox_object_name)
        if self.comboBox is None:
            print(f"提示 : 获取 {self.comboBox_object_name} 对应的 comboBox 列表失败!")
            print(f"提示 : 子任务结束!")
            return
        self.textedit_object_name = "textEdit_localtion_upload_configfile"
        self.textedit : QTextEdit = self.parent().findChild(QTextEdit,self.textedit_object_name)
        if self.textedit is None:
            print(f"提示 : 获取 {self.textedit_object_name} 对应的 textEdit 列表失败!")
            print(f"提示 : 子任务结束!")
            return
        
        

        # 创建子线程
        # self.workerthread = Worker_Thread()



        # 绑定信号
        # self.workerthread.finished.connect(lambda : QMessageBox.information(self.parent_widget,"提示","任务完成!"))
        # self.workerthread.finished.connect(lambda : self.Task_Finish.emit())    # 子线程运行结束代表该员工类的任务结束
        # self.workerthread.finished.connect(lambda : self.workerthread.quit())   # 线程结束，销毁线程
        # self.workerthread.finished.connect(lambda : self.deleteLater())
        # self.workerthread.finished.connect(lambda : self.task_button.setEnabled(True))
        # self.workerthread.thread_task_data.connect(lambda task_data: print(task_data))


        # 启动子线程,开始执行任务
        self.task_button.setEnabled(False)

        text = self.textedit.toPlainText()
        saveas_file_name = QInputDialog.getText(self.parent_widget,"正在另存为 ... : ","输入保存的文件名 :")[0]
        
        if saveas_file_name == "":
            return
        else:
            saveas_file_name += ".yaml"

        saveas_path = pathlib.Path("./Data/Product_Upload_Config_File").joinpath(saveas_file_name).absolute().resolve()
        if saveas_path.exists():
            saveas_path.mkdir(parents=True, exist_ok=True)
        saveas_path = pathlib.Path("./Data/Product_Upload_Config_File").joinpath(saveas_file_name).absolute().resolve().__str__()
        with open(file=saveas_path,mode="w",encoding="utf-8") as f:
            f.write(text)
            f.close()
        is_open_update_directory = QMessageBox.question(self.parent_widget,"提示",f"另存为成功!\n路径 : {saveas_path}\n是否需要打开路径呢!",QMessageBox.Yes|QMessageBox.No)
        if is_open_update_directory == QMessageBox.Yes:
            os.startfile(pathlib.Path(saveas_path).parent.absolute().resolve().__str__())





        self.task_button.setEnabled(True)
        # self.workerthread.start()
        

        


















if __name__ == "__main__":
    import sys
    from PySide6.QtWidgets import QApplication
    app = QApplication(sys.argv)
    # 编写 控制台 程序
    staff = Staff_Saveas_Upload_Config_File(app)
    staff.RunTask()
    
    sys.exit(app.exec_())